package logrus

import (
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"second-go/config"
	"second-go/log/logger"
)

func RegisterLog(lc config.LogConfig) error {
	log := logrus.New()
	log.SetFormatter(&logrus.TextFormatter{})
	log.SetReportCaller(true)
	err := customizeLogFromConfig(log, lc)
	if err != nil {
		return errors.Wrap(err, "")
	}

	logger.SetLogger(log)
	return nil
}

func customizeLogFromConfig(log *logrus.Logger, lc config.LogConfig) error {
	log.SetReportCaller(lc.EnableCaller)

	if lc.FileName != "" {
		_ = os.MkdirAll(filepath.Dir(lc.FileName), 0777)
		f, _ := os.OpenFile(lc.FileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
		log.SetOutput(f)
	} else {
		log.SetOutput(os.Stdout)
	}

	l := &log.Level
	err := l.UnmarshalText([]byte(lc.Level))
	if err != nil {
		return errors.Wrap(err, "")
	}
	log.SetLevel(*l)
	return nil
}
